<?php

class AjaxController extends Backend {

    public function init() {
        parent::init();
        $this->load->model("form");
    }

    public function indexAction() {
        
    }

    public function optionsAction($table = '') {
        Yaf_Dispatcher::getInstance()->disableView();
        header("Content-Type: application/json; charset=utf-8");
        $q = $this->_request->getPost("q");
        $name = $table == 'tag' || $table == 'country' ? 'name' : 'title';
        $searchlist = $this->db->all("SELECT id AS `value`,{$name} AS text FROM {pre}{$table} WHERE {$name} LIKE ? OR diyname LIKE ? LIMIT 10", array("%{$q}%", "%{$q}%"));
        echo json_encode(array_values($searchlist));
    }

    public function uploadAction() {
        $code = -1;
        $content = NULL;
        if ($_FILES['file']['name']) {
            if (!$_FILES['file']['error']) {
                if (stripos($_FILES['file']['name'], '.') == FALSE) {
                    $ext = substr($_FILES['file']['type'], stripos($_FILES['file']['type'], '/') + 1);
                } else {
                    $extarr = explode('.', $_FILES['file']['name']);
                    $ext = end($extarr);
                }
                $filename = date("YmdHis") . '.' . $ext;
                $imgurl = '/uploads/editor/' . date("Ymd") . '/' . $filename;
                $uploadresult = Tools::savefile($_FILES["file"]["tmp_name"], $imgurl);
                if ($uploadresult) {
                    $code = 0;
                    $content = $imgurl;
                } else {
                    $code = -1;
                }
            } else {
                echo $message = 'Ooops! ' . $_FILES['file']['error'];
            }
        }
        echo json_encode(array('code' => $code, 'content' => $content));
        return FALSE;
    }

    public function checksiteAction() {
        $one = $this->db->one("SELECT COUNT(*) AS nums FROM {pre}site WHERE status = ?", array('hidden'));
        echo json_encode(array('code' => 0, 'content' => $one['nums']));
        return FALSE;
    }

    public function pullsiteAction() {
        $code = -1;
        $content = '';
        $url = $this->_request->getPost("url");
        if ($url) {
            $content = $this->site->pullsite($url);
            $code = $content ? 0 : -1;
        }
        echo json_encode(array('code' => $code, 'content' => $content));
        return FALSE;
    }

}
